package com.yzycoc.hamster.demo.time202505.time20250523.test;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.db.Db;
import cn.hutool.db.DbUtil;
import cn.hutool.db.Entity;
import cn.hutool.db.ds.simple.SimpleDataSource;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.yzycoc.hamster.demo.time202505.time20250523.info.ApiText;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class QianfanAIChat {

    // 百度千帆API配置 - 请替换为您自己的Bearer Token
    private static final String BEARER_TOKEN = "Bearer bce-v3/ALTAK-ltsES4gQgCORlrBGoiNPz/c8f139811d18f5097cbb0fac0002570070bcc7a8";
    private static final String API_URL = "https://qianfan.baidubce.com/v2/chat/completions";

    public static void main(String[] args) {
        // 1. 创建数据源
        SimpleDataSource dataSource = new SimpleDataSource(
                "jdbc:mysql://175.178.243.28:23306/cqrobot?useSSL=false&serverTimezone=Asia/Shanghai",
                "cqrobot",
                "936642284"
        );
        Db db = DbUtil.use(dataSource);
        while (true){


            // 4. 插入数据库
            try {
                ApiText apiText = getInsertSql();
                if(apiText == null){
                    ThreadUtil.sleep(30 * 1000L);
                    continue;
                }
                // 3. 转为 Entity（字段名需与数据库字段一致）
                Entity entity = Entity.create("api_text")
                        .set("create_date", apiText.getCreateDate())
                        .set("create_name", apiText.getCreateName())
                        .set("text", apiText.getText())
                        .set("author", apiText.getAuthor())
                        .set("type", apiText.getType())
                        .set("deleted", apiText.getDeleted());
                System.out.println("\n准备插入数据：\n" + entity.toString());
                //
                // 123
                // int row = db.insert(entity);
                //
                // 123
                // System.out.println("插入成功，影响行数：" + row);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("插入失败：" + e.getMessage());
            }
            ThreadUtil.sleep(30 * 1000L);
        }


    }
    public static ApiText getInsertSql(){
        try {
            // 构建请求参数
            String requestBody = buildRequestBody("现在一个人正在寻求的安慰，请给一个100~300字左右安慰的回答吧,可以讲些故事，也可以是经典名言，返回给我的内容我将直接复制,不需要你额外说其他的话术和注释。");
            // 发送请求并获取响应
            String response = chatWithQianfan(requestBody);
            //System.out.println("\nAI响应: " + response);
            String outputContent = printResponseContent(response);
            System.err.println("\n解析后的内容:\n " + outputContent);
            ApiText apiText = new ApiText();
            apiText.setText(ReUtil.delAll("（.*?）", ReUtil.delAll("(.*?)", outputContent)));
            apiText.setAuthor("");
            apiText.setCreateDate(DateUtil.now());
            apiText.setCreateName("百度AI");
            apiText.setType(30);
            apiText.setDeleted(0);
            return apiText;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 解析并返回响应内容
     */
    private static String printResponseContent(String jsonResponse) {
        // 初始化一个StringBuilder来构建输出内容
        StringBuilder output = new StringBuilder();
        // 解析JSON响应
        cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(jsonResponse);
        // 获取choices数组
        List<cn.hutool.json.JSONObject> choices = jsonObject.getJSONArray("choices").toList(cn.hutool.json.JSONObject.class);
        for (cn.hutool.json.JSONObject choice : choices) {
            // 检查message对象中是否有content字段
            if (choice.containsKey("message")) {
                cn.hutool.json.JSONObject message = choice.getJSONObject("message");
                // 如果有content字段，添加到输出中
                if (message.containsKey("content")) {
                    String content = message.getStr("content");
                    output.append(content);
                }
                // 如果有tool_calls字段，添加到输出中
                if (message.containsKey("tool_calls")) {
                    List<cn.hutool.json.JSONObject> toolCalls = message.getJSONArray("tool_calls").toList(cn.hutool.json.JSONObject.class);
                    // 添加每个工具调用的参数
                    for (cn.hutool.json.JSONObject toolCall : toolCalls) {
                        cn.hutool.json.JSONObject function = toolCall.getJSONObject("function");
                        String arguments = function.getStr("arguments");
                        output.append(arguments).append("\n");
                    }
                }
            }
        }
        // 返回构建的输出内容
        return output.toString();
    }

    /**
     * 与千帆AI对话
     */
    public static String chatWithQianfan(String requestBody) throws Exception {
        // 发送POST请求
        HttpResponse response = HttpRequest.post(API_URL)
                .header("Authorization", BEARER_TOKEN)
                .header("Content-Type", "application/json")
                .body(requestBody)
                .execute();

        // 解析响应
        if (response.isOk()) {
            return response.body();
        } else {
            throw new RuntimeException("API请求失败: " + response.getStatus() + " - " + response.body());
        }
    }

    /**
     * 构建请求体
     */
    private static String buildRequestBody(String message) {
        // 构建messages
        List<Map<String, String>> messages = new ArrayList<>();
        Map<String, String> userMessage = new HashMap<>();
        userMessage.put("role", "user");
        userMessage.put("content", message);
        messages.add(userMessage);

        // 构建tools
        List<Map<String, Object>> tools = new ArrayList<>();
        Map<String, Object> tool = new HashMap<>();
        tool.put("type", "function");

        Map<String, Object> function = new HashMap<>();
        function.put("name", "get_current_weather");
        function.put("description", "天气查询工具");

        Map<String, Object> parameters = new HashMap<>();
        Map<String, Object> properties = new HashMap<>();

        Map<String, Object> locationProp = new HashMap<>();
        locationProp.put("description", "地理位置，精确到区县级别");
        locationProp.put("type", "string");

        Map<String, Object> timeProp = new HashMap<>();
        timeProp.put("description", "时间，格式为YYYY-MM-DD");
        timeProp.put("type", "string");

        properties.put("location", locationProp);
        properties.put("time", timeProp);

        parameters.put("properties", properties);
        parameters.put("required", new String[]{"location", "time"});
        parameters.put("type", "object");

        function.put("parameters", parameters);
        tool.put("function", function);
        //tools.add(tool);

        // 构建完整请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "ernie-4.0-8k");
        requestBody.put("messages", messages);
        requestBody.put("tools", tools);
        requestBody.put("stream", false);
        requestBody.put("tool_choice", "auto");

        return JSONUtil.toJsonStr(requestBody);
    }
}